package hu.arguscab.game;


import hu.arguscab.ai.util.AbstractQuadTreeCreator;
import hu.arguscab.ai.util.QuadNode;
import hu.arguscab.ai.util.Rect;
import hu.arguscab.physic.Vector;

public class QuadTreeCreator extends AbstractQuadTreeCreator<Map, Integer, Vector> {

	public QuadTreeCreator(Map obj) {
		super(obj);
	}

	@Override
	protected QuadNode<Vector> createNode(Map map, Rect r) {
		QuadNode<Vector> node = new QuadNode<Vector>(r);
		node.setData(node.getCenter());
		node.setHomogeneous(isHomogeneous(map, r));
		return node;
	}
	
	@Override
	protected Rect createRootRect(Map map) {
		return new Rect(0, 0, map.getWidth(), map.getHeight());
	}	


	private boolean isHomogeneous(Map map, Rect area) {
		int max = area.getW() * area.getH();
		int obstaclePixel = 0;
		for ( int x = area.getX(); x < area.getX2(); ++x ) {
			for ( int y = area.getY(); y < area.getY2(); ++y ) {
				for ( Rect obj : map.getObjects() ) {
					if ( isInRect(obj, x, y) == true )
						++obstaclePixel;
				}
			}
		}
		float obstaclePercent = ((float)obstaclePixel) / max;
		float walkablePercent = 1 - obstaclePercent;
		if ( Math.max(obstaclePercent, walkablePercent) == 1.0f )
			return true;
		return false;
	}
	
	private boolean isInRect(Rect area, int x, int y) {
		if ( x >= area.getX() && x <= area.getX2() ) {
			if ( y >= area.getY() && y <= area.getY2() ) {
				return true;
			}
		}
		return false;
	}

	@Override
	protected boolean isIn(Vector vec, QuadNode<Vector> node) {
		return isInRect(node.getRect(), (int)vec.getX(), (int)vec.getY());
	}
}
